package com.tian.mall;

import com.sun.mail.util.MailSSLSocketFactory;
import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.security.GeneralSecurityException;
import java.util.Date;
import java.util.Properties;

/**
 * @author zhumengping
 * @title: EmailImpl
 * @projectName zhump-cloud
 * @date 2023/8/2 14:26
 */
public class EmailImpl implements IEmail{

    public static final Logger log = LogManager.getLogger(EmailImpl.class);


    private Session getSession(String host,String port){
        Properties props = new Properties();
        // 设置服务器
        props.setProperty("mail.transport.protocol", "smtp");
        props.setProperty("mail.smtp.host", host);
        props.setProperty("mail.smtp.port", port);
        props.setProperty("mail.smtp.auth", "true");
        props.put("mail.smtp.ssl.enable", "true");
        // 开启安全协议
        MailSSLSocketFactory sf = null;
        try {
            sf = new MailSSLSocketFactory();
            sf.setTrustAllHosts(true);
        } catch (GeneralSecurityException e1) {
            e1.printStackTrace();
        }
        props.put("mail.smtp.ssl.socketFactory", sf);

        Session session = Session.getInstance(props);
        session.setDebug(false);
        return session;
    }


    /**
     * <pre>
     *     具体事项
     * </pre>
     *
     * @param request 邮箱服务器地址
     * @return void
     * @author zhump
     * @date 2023/8/2 10:33
     */
    @Override
    public void normalMail(EmailRequestEntity request){
        log.info("【发送邮件开始时间】:{}",DateUtils.getDateFromString(new Date()));
        EmailEnums enums = EmailEnums.getInstance(request.getMailType());
        Session session = getSession(enums.getMailHost(), enums.getMailPort());
        MimeMessage message = createEmail(session,request);
        Transport transport = null;
        try {
            transport = session.getTransport();
            transport.connect(request.getSendMail(),request.getSendMailPwd());
            transport.sendMessage(message,message.getAllRecipients());
            log.info("【发送邮件结束时间】:{}",DateUtils.getDateFromString(new Date()));
        }catch (Exception e){
            log.error("[normalMail()] send exception:{}",e);
        }finally {
            try {
                if (null != transport){
                    transport.close();
                }
            } catch (MessagingException e) {
                log.error("[normalMail()] send exception:{}",e);
            }
        }
    }

    public static MimeMessage createEmail(Session session,EmailRequestEntity request) {
        log.info("【serverName】:{},【mailSource】:{},【mailAccount】:{}",request.getServerName(),request.getChannel().getDesc(),request.getReceiveMail());
        MimeMessage mimeMessage = new MimeMessage(session);
        try {
            mimeMessage.setFrom(new InternetAddress(request.getSendMail(),"发件人","UTF-8"));
            mimeMessage.setRecipient(MimeMessage.RecipientType.TO,new InternetAddress(request.getReceiveMail(),request.getReceiveName(),"UTF-8"));
            mimeMessage.setSubject(request.getSubject(),"UTF-8");
            mimeMessage.setContent(request.getSendContent(),"text/html;charset=UTF-8");
            mimeMessage.setSentDate(new Date());
            mimeMessage.saveChanges();
        }catch (Exception e){
            log.error("[createEmail()] send exception:{}",e);
        }
        return mimeMessage;

    }
}
